import { quality } from "../../shared/face/enums";
import sdk from '../index';

export enum CounterKey {
    玩家总数 = 'playerCont',
    邮件ID = 'mailCont',
    系统邮件版本号 = 'mailSysCont',
    装备ID = 'equipCont',
    审核记录ID = 'reviewCont',
    // 品质计数器
    品质F计数 = 'qualityF',
    品质D计数 = 'qualityD',
    品质C计数 = 'qualityC',
    品质B计数 = 'qualityB',
    品质A计数 = 'qualityA',
    品质S计数 = 'qualityS',
    品质SS计数 = 'qualitySS',
    品质SSS计数 = 'qualitySSS',
    品质SR计数 = 'qualitySR',
    品质SSR计数 = 'qualitySSR'
}

class Counter {
    private CounterMap: Map<string, number> = new Map();
    
    // 品质概率配置 - 表示需要多少个低品质才能出一个高品质
    private readonly QUALITY_THRESHOLDS: Record<quality, number> = {
        [quality.F]: 0,   // F级不需要阈值
        [quality.D]: 5,  // 30个F才能出1个D
        [quality.C]: 1,  // 20个D才能出1个C
        [quality.B]: 1,  // 20个C才能出1个B
        [quality.A]: 1,  // 10个B才能出1个A
        [quality.S]: 1,  // 15个A才能出1个S
        [quality.SS]: 1, // 24个S才能出1个SS
        [quality.SSS]: 1, // 4个SS才能出1个SSS
        [quality.SR]: 2,  // 3个SSS才能出1个SR
        [quality.SSR]: 1, // 2个SR才能出1个SSR
    };

    async init() {
        let data = await sdk.db.find('counter');
        console.log('Counter初始化，数据库数据:', data);
        if (data.length > 0) {
            for (let i = 0; i < data.length; i++) {
                const e = data[i];
                this.CounterMap.set(e.key,e.val)
            }
        }
        console.log('Counter初始化完成，内存数据:', Array.from(this.CounterMap.entries()));
    }
    /**
     * 生成0到当前计数器值的随机数
     * @param key 计数器键名
     */
    random(key: string) {
        let now = this.CounterMap.get(key) || 1;
        const randomValue = sdk.tool.common.random(0, now);
        return randomValue;
    }
    get(key: string) {
        let now = this.CounterMap.get(key) || 0;
        now += 1;
        this.CounterMap.set(key, now);
        // 立即保存到数据库
        return sdk.tool.common.formatNumberWithLeadingZero(Number(now));
    }
    getNum(key:string,look:boolean = false){
        let now = this.CounterMap.get(key) || 0;
        if(!look){
            now += 1;
            this.CounterMap.set(key, now);
        }
        return now;
    }
    async save() {
        const operations = Array.from(this.CounterMap.entries()).map(
            ([key, val]) => sdk.db.update('counter', { key:key }, {val:val})
        );
        await Promise.all(operations);
        console.log('计数器 存档完成')
    }
    
    /**
     * 获取随机品质
     * 根据概率系统返回品质等级
     * @returns {quality} 返回的品质等级
     */
    getQuality(): quality {
        // 从低品质开始检查，看是否达到升级条件
        const qualityLevels = [
            quality.F, quality.D, quality.C, quality.B, 
            quality.A, quality.S, quality.SS, quality.SSS, quality.SR, quality.SSR
        ];
        
        // 检查每个品质，看是否达到升级条件
        for (let i = 0; i < qualityLevels.length - 1; i++) {
            const currentQuality = qualityLevels[i];
            const nextQuality = qualityLevels[i + 1];
            const counterKey = `quality${currentQuality}`;
            // console.log(`计数器键名: ${counterKey}`);
            const currentCount = this.getNum(counterKey, true); // 只查看不增加计数
            const threshold = this.QUALITY_THRESHOLDS[nextQuality];
            
            // console.log(`检查 ${currentQuality} -> ${nextQuality}: 当前计数=${currentCount}, 阈值=${threshold}`);
            
            // 如果当前品质的计数达到阈值，返回下一个品质并重置当前品质计数
            if (currentCount >= threshold) {
                // console.log(`✓ 达到阈值！返回 ${nextQuality} 品质`);
                // 重置当前品质的计数
                this.CounterMap.set(counterKey, 0);
                
                // 如果达到最高品质SSR，清空所有品质计数器
                if (nextQuality === quality.SSR) {
                    console.log('🎉 出现最高品质SSR！清空所有品质计数器');
                    this.CounterMap.set('qualityF', 0);
                    this.CounterMap.set('qualityD', 0);
                    this.CounterMap.set('qualityC', 0);
                    this.CounterMap.set('qualityB', 0);
                    this.CounterMap.set('qualityA', 0);
                    this.CounterMap.set('qualityS', 0);
                    this.CounterMap.set('qualitySS', 0);
                    this.CounterMap.set('qualitySSS', 0);
                    this.CounterMap.set('qualitySR', 0);
                    this.CounterMap.set('qualitySSR', 0);
                    return nextQuality;
                }
                
                // 增加下一个品质的计数
                const nextCounterKey = `quality${nextQuality}`;
                this.getNum(nextCounterKey);
                return nextQuality;
            }
        }
        
        // 如果所有升级条件都未达到，返回F级并增加F级计数
        // console.log('✗ 所有品质都未达到阈值，返回 F 品质');
        const fCounterKey = `quality${quality.F}`;
        // console.log(`F级计数器键名: ${fCounterKey}`);
        const fCount = this.getNum(fCounterKey); // 增加F级计数
        // console.log(`F级计数增加到: ${fCount}`);
        return quality.F;
    }
}
export default new Counter();